1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.collect;
18
19 import com.google.caliper.AfterExperiment;
20 import com.google.caliper.BeforeExperiment;
21 import com.google.caliper.Benchmark;
22 import com.google.caliper.Param;
23 import com.google.common.base.Function;
24 import com.google.common.collect.MapMaker;
25 import com.google.common.primitives.Ints;
26
27 import java.util.Map;
28 import java.util.Random;
29 import java.util.concurrent.atomic.AtomicLong;
30
31
32
33
34
35
36 public class MapMakerSingleThreadBenchmark {
37 @Param({"1000", "2000"}) int maximumSize;
38 @Param("5000") int distinctKeys;
39 @Param("4") int segments;
40
41
42
43 @Param("2.5") double concentration;
44
45 Random random = new Random();
46
47 Map<Integer, Integer> cache;
48
49 int max;
50
51 static AtomicLong requests = new AtomicLong(0);
52 static AtomicLong misses = new AtomicLong(0);
53
54 @BeforeExperiment void setUp() {
55
56
57 max = Ints.checkedCast((long) Math.pow(distinctKeys, concentration));
58
59 cache = new MapMaker()
60 .concurrencyLevel(segments)
61 .maximumSize(maximumSize)
62 .makeComputingMap(
63 new Function<Integer, Integer>() {
64 @Override public Integer apply(Integer from) {
65 return (int) misses.incrementAndGet();
66 }
67 });
68
69
70
71
72
73 while (cache.get(nextRandomKey()) < maximumSize) {}
74
75 requests.set(0);
76 misses.set(0);
77 }
78
79 @Benchmark int time(int reps) {
80 int dummy = 0;
81 for (int i = 0; i < reps; i++) {
82 dummy += cache.get(nextRandomKey());
83 }
84 requests.addAndGet(reps);
85 return dummy;
86 }
87
88 private int nextRandomKey() {
89 int a = random.nextInt(max);
90
91
92
93
94
95
96
97 return (int) Math.pow(a, 1.0 / concentration);
98 }
99
100 @AfterExperiment void tearDown() {
101 double req = requests.get();
102 double hit = req - misses.get();
103
104
105 System.out.println("hit rate: " + hit / req);
106 }
107
108
109
110
111 }